package Meituan;

import com.google.common.collect.Lists;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author: leiwenkang
 * @date: 2019/11/5
 * @time: 15:53
 */
public class Test34 {
    public static void main(String[] args) {
        List<Integer> list1 = Lists.newArrayList();
        list1.add(10);
        list1.add(20);
        list1.add(30);
        List<Integer> list2 = Lists.newArrayList();
        list2.add(20);
        list2.add(30);
        list2.add(40);
        double overlapRate = calOverlapRate(list1, list2);
        double inverseNumberRate = calInverseNumberRate(list1, list2);
        System.out.println(overlapRate);
        System.out.println(inverseNumberRate);

    }

    // 计算重叠率
    private static double calOverlapRate(List list1, List list2){
        Set set1 = new HashSet<>(list1);
        Set set2 = new HashSet<>(list2);
        set2.retainAll(set1);
        return  (double) set2.size() * 100 / set1.size();
    }

    // 计算逆序数
    private static double calInverseNumberRate(List topNIdList1, List topNIdList2){
        Map<Long, Integer> poiDoublePosMap1 = createId2PosMap(topNIdList1);
        Map<Long, Integer> poiDoublePosMap2 = createId2PosMap(topNIdList2);
        return calInverseNumber(poiDoublePosMap1, poiDoublePosMap2);
    }

    private static <T> double calInverseNumber(Map<T, Integer> v1, Map<T, Integer> v2) {
        Set<T> both = new HashSet<>(v1.keySet());
        both.retainAll(v2.keySet());
        double inverseNumber = 0;

        for (T i : both) {
            for (T j : both) {
                if (v2.get(j) > v2.get(i) && v1.get(i) > v1.get(j)) {
                    inverseNumber++;
                }
            }
        }
        return inverseNumber;
    }

    /**
     * 把poiId列表转为poiId到位置的映射表
     */
    public static <T> Map<T, Integer> createId2PosMap(List<T> idList){

        Map<T, Integer> id2PosMap = new HashMap<>();

        if(null == idList){
            return id2PosMap;
        }

        int i = 0;
        for(T poiId : idList){
            i++;
            id2PosMap.put(poiId, i);
        }

        return id2PosMap;

    }


}
